package com.numberone.master.common.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.numberone.master.common.lianlianpay.util.SSLClient;
import com.numberone.master.common.utils.StringUtils;
import com.numberone.master.common.yunzhanghu.DesBase;
import com.numberone.master.common.yunzhanghu.HmacSha256;
import com.numberone.master.common.yunzhanghu.bean.OrderBean;

public class HttpClientUtil {
	/**
	 * POST请求
	 * 
	 * @param url
	 *            地址
	 * @param parms
	 *            参数
	 * @param charset
	 *            返回数据编码格式
	 * @return
	 */
	public static String doPost(String url, String parms, String charset) {
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		try {
			System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
			httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			// 添加头信息
			httpPost.addHeader("Content-Type", "application/json");
			StringEntity se = new StringEntity(parms);
			se.setContentEncoding(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
			httpPost.setEntity(se);
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	/**
	 * 参数为JSON格式POST请求
	 * 
	 * @param url
	 *            地址
	 *            参数 JSON格式
	 * @param charset
	 *            返回数据编码格式
	 * @return
	 */
	public static String doJsonPost(String url, String jsonstr, String charset, String dealer_id, String substring) {
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		try {
			System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
			httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			// 添加头信息
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			httpPost.addHeader("dealer-id", dealer_id);
			httpPost.addHeader("request-id", substring);
			StringEntity se = new StringEntity(jsonstr);
			se.setContentEncoding("UTF-8");
			se.setContentType("application/json;charset=UTF-8");
			httpPost.setEntity(se);
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public static Map<String, Object> getTokenByPost(String httpUrl,String param,String dealer_id) throws Exception {
	
				
		Map<String, Object> requestTokenInform = Maps.newHashMap();
		SslUtils.ignoreSsl();
		URL url = new URL(httpUrl);
		// 创建http链接对象
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
		if (con instanceof HttpsURLConnection) {
			SSLContext sc = SSLContext.getInstance("TLSv1.2");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
			((HttpsURLConnection) con).setSSLSocketFactory(sc.getSocketFactory());
			((HttpsURLConnection) con).setHostnameVerifier(new TrustAnyHostnameVerifier());
		}
		con.setRequestProperty("dealer-id", dealer_id);
		con.setRequestProperty("request-id", String.valueOf(System.currentTimeMillis()));
		con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
		// 设置请求方式
		con.setRequestMethod("POST");
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setUseCaches(false);
		OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
		osw.write(param);
		osw.flush();
		osw.close();
		// 获取请求状态 code 和 Message
		int requestStatus = con.getResponseCode();
		String requestMessage = con.getResponseMessage();
		requestTokenInform.put("requestStatus", requestStatus);
		requestTokenInform.put("requestMessage", requestMessage);
		// 获取请求返回内容并设置编码为UTF-8
		BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
		// 将返回数据拼接为字符串
		StringBuffer sb = new StringBuffer();
		// 临时字符串
		String temp = null;
		// 获取数据
		while ((temp = reader.readLine()) != null) {
			sb.append(temp);
		}
		// 关闭流
		reader.close();
		requestTokenInform.put("tokenData", sb.toString());
		return requestTokenInform;
	}


	public static Map<String, Object> getTokenByGet(String httpUrl,String param,String dealer_id) throws Exception {

		Map<String, Object> requestTokenInform = Maps.newHashMap();
		SslUtils.ignoreSsl();

        //get请求，拼接参数
        httpUrl=httpUrl+"?"+param;

		URL url = new URL(httpUrl);
		// 创建http链接对象
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
		if (con instanceof HttpsURLConnection) {
			SSLContext sc = SSLContext.getInstance("TLSv1.2");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
			((HttpsURLConnection) con).setSSLSocketFactory(sc.getSocketFactory());
			((HttpsURLConnection) con).setHostnameVerifier(new TrustAnyHostnameVerifier());
		}
		con.setRequestProperty("dealer-id", dealer_id);
		con.setRequestProperty("request-id", String.valueOf(System.currentTimeMillis()));

		// 获取请求状态 code 和 Message
		int requestStatus = con.getResponseCode();
		String requestMessage = con.getResponseMessage();
		requestTokenInform.put("requestStatus", requestStatus);
		requestTokenInform.put("requestMessage", requestMessage);
		// 获取请求返回内容并设置编码为UTF-8
		BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
		// 将返回数据拼接为字符串
		StringBuffer sb = new StringBuffer();
		// 临时字符串
		String temp = null;
		// 获取数据
		while ((temp = reader.readLine()) != null) {
			sb.append(temp);
		}
		// 关闭流
		reader.close();
		requestTokenInform.put("tokenData", sb.toString());
		return requestTokenInform;
	}

	public static void main(String[] args) throws Exception {
		// String url =
		// "https://218.207.75.17:8060/OAuth/restOauth2Server/access_token";
		// String jsonStr =
		// "grant_type=client_credentials&client_id=20190128000101703&client_secret=95cfe896bgtb74120ecef2019c14abt8";

		/*
		 * String url =
		 * "https://218.207.75.17:8060/OpenEbus/httpService/UserQueryService?method=BJSHQueryTaocanUnionAndCheck&format=json&access_token=2d36c0b16b1df366c98fc1e0f53c077ce7faf171&COMMANDID=311A280562";
		 * String jsonStr =
		 * "{\"TELNUM\" : \"1440152014323\",\"BillCycle\" : \"201806\",\"PUBLICPARAM\":\"\"}"
		 * ; String httpOrgCreateTestRtn = HttpClientUtil.doJsonPost(url,
		 * jsonStr, "GBK"); System.out.println(httpOrgCreateTestRtn);
		 */
		// 商户代码
		String dealer_id = "01637680";
		// 代征主体
		String broker_id = "yiyun73";
		String orderNo = "WLWK-" + StringUtils.getDateString(5);
		OrderBean bean = new OrderBean(orderNo, dealer_id, broker_id, "石艳林", "6236681370003480461",
				"340826199009218716", "2.00", "物联网卡提现", "物联网卡提现");
		String orderJson = JSONObject.toJSONString(bean);

		//deskey
		 String deskey="22kR1XgtB3O3zUPHo9gXydK1";
		//appKey
		 String appKey="XZ3oVGbb83QreuJ93q7F3PNTM6t4N7AQ";
		/*String httpOrgCreateTestRtn = HttpClientUtil.doJsonPost(
				"https://api-jiesuan.yunzhanghu.com/api/payment/v1/order-realtime", orderJson, "utf-8", dealer_id,
				String.valueOf(System.currentTimeMillis()));*/

		byte[] enc = DesBase.TripleDesEncrypt(orderJson.getBytes("utf-8"), deskey.getBytes("utf-8"));

		byte[] enc64 = Base64.encodeBase64(enc);

		String data=new String (enc64);

		String param="data="+data;

		param+="&mess="+StringUtils.getRandomNumberString(6);
		String timestamp=String.valueOf(System.currentTimeMillis());
		timestamp=timestamp.substring(0, timestamp.length()-3);

		param+="&timestamp="+timestamp;

		String signmessage=param+"&key="+appKey;
		System.out.println(signmessage);

		String sign=HmacSha256.sha256HMAC(signmessage,appKey);

		param+="&sign="+sign;

		param+="&sign_type=sha256";
		param=URLEncoder.encode(param);
		System.out.println(param);
		param=param.replace("%3D", "=").replace("%26", "&");
		System.out.println(param);
		System.out.println(getTokenByPost("https://api-jiesuan.yunzhanghu.com/api/payment/v1/order-realtime",param,dealer_id));

	}
}
